<?php
/**
 * Created by PhpStorm.
 * User: zyw
 * Date: 2018-06-22
 * Time: 23:46
 */

try{
    set_time_limit(0);
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    date_default_timezone_set('Asia/Shanghai');
    require_once "../../db/video_db.php";

    $postData = file_get_contents('php://input');
    $body = json_decode($postData, true);

    $nickname   = isset($body["u"]["nickname"]) ? $body["u"]["nickname"] : "";
    $source     = isset($body["u"]["source"])   ? $body["u"]["source"] : "";
    $mobile     = isset($body["u"]["mobile"])   ? $body["u"]["mobile"] : "";
    $sex        = isset($body["u"]["sex"])      ? $body["u"]["sex"] : 0; //  0:默认 1:男 2:女
    $birth      = isset($body["u"]["birth"])    ? $body["u"]["birth"] : 0; //时间戳
    $avator     = isset($body["u"]["avator"])   ? $body["u"]["avator"] : ""; // {"u":"地址", "w":"宽", "h":"高"}
    $regdate    = isset($body["u"]["regdate"])  ? $body["u"]["regdate"] : 0;//时间戳
    $city       = isset($body["u"]["city"])     ? $body["u"]["city"] : "";
    $sign       = isset($body["u"]["sign"])     ? $body["u"]["sign"] : "";
    $loginTime  = isset($body["u"]["login_time"]) ? $body["u"]["login_time"] : 0;

    $s_d_uid  = isset($body["s"]["d_uid"]) ? $body["s"]["d_uid"] : "";
    $s_source_id  = isset($body["s"]["source_id"]) ? $body["s"]["source_id"] : "";
    $s_nickname   = isset($body["s"]["nickname"]) ? $body["s"]["nickname"] : "";
    $s_mobile     = isset($body["s"]["mobile"])   ? $body["s"]["mobile"] : "";
    $s_sex        = isset($body["s"]["sex"])      ? $body["s"]["sex"] : 0; //  0:默认 1:男 2:女
    $s_birth      = isset($body["s"]["birth"])    ? $body["s"]["birth"] : 0; //时间戳
    $s_avator     = isset($body["s"]["avator"])   ? $body["s"]["avator"] : ""; // {"u":"地址", "w":"宽", "h":"高"}
    $s_regdate    = isset($body["s"]["regdate"])  ? $body["s"]["regdate"] : 0;//时间戳
    $s_sign       = isset($body["s"]["sign"])     ? $body["s"]["sign"] : "";
    $s_like_num   = isset($body["s"]["like_num"])     ? $body["s"]["like_num"] : 0;//点赞数
    $s_fans_num   = isset($body["s"]["fans_num"])     ? $body["s"]["fans_num"] : 0;//粉丝数

    if(empty($avator["u"]) || empty($avator["w"]) || empty($avator["h"])){
        $res = array("code"=>-1, "result"=>null, "msg"=>'用户头像数据不正确,例：{"u":"地址", "w":"宽", "h":"高"}');
        echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
    }
    if(!in_array($sex, array(0, 1, 2))){
        $res = array("code"=>-1, "result"=>null, "msg"=>"用户性别数据不正确, 例：0:默认 1:男 2:女");
        echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
    }
    if(empty($nickname) || empty($mobile) || empty($birth) || empty($avator) || empty($regdate) || empty($source)){
        $res = array("code"=>-1, "result"=>null, "msg"=>"用户昵称,手机号,生日,头像URL地址,注册日期,用户来源 不能为空");
        echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
    }
    $pattern = '/(\s)+/is';

    $nickname = str_replace('\'', '', $nickname);
    $nickname = trim($nickname);
    $nickname = preg_replace($pattern, "\n", $nickname);

    $sign = str_replace('\'', '', $sign);
    $sign = trim($sign);
    $sign = preg_replace($pattern, "\n", $sign);

    $sql = "select * from t_user where mobile='".$mobile."' limit 1";
    $userInfo = video_db::fetch($sql);
    if(!empty($userInfo)){
        $res = array("code"=>-1, "result"=>null, "msg"=>"该手机号用户已存在");
        echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
    }
    $city_id = 0;
    if($city){
        $sql = "select * from t_district where `name` like '%".$city."' limit 1";
        $district = video_db::fetch($sql);
        $city_id = !empty($district["id"]) ? $district["id"] : 0;
    }
    $mobile = (string)$mobile; $sex=(int)$sex; $birth=(int)$birth;$source=(string)$source;$regdate=(string)$regdate;$loginTime=(int)$loginTime;

    //查询抖音uid是否存在
    $sql = "select * from t_user_import where d_uid='".$s_d_uid."' and uid is not null limit 1";
    $import_info = video_db::fetch($sql);
    $uid='';
    if(!empty($import_info)){//如果抖音uid存在   查询是否导入的抖音id用户是否有uid
        $uid=$import_info['uid'];//抖音uid在本项目中生成过用户uid
    }
    if(empty($uid)){//如果抖音uid未在本项目中生成过uid
/////////-----------写入user
        $sql = "insert into t_user(nickname, mobile, username, sex, birth, user_type, user_source, regdate, city_id, sign, last_login)values";
        $sql.= "('".$nickname."', '".$mobile."', '".$mobile."', '".$sex."', '".$birth."', 3, '".$source."', '".$regdate."','".$city_id."', '".$sign."','".$loginTime."')";
        $uid = video_db::execute($sql);
        if(empty($uid)){
            $res = array("code"=>-1, "result"=>null, "msg"=>"用户添加失败");
            echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
        }
        $sql = "insert into t_img(path, w, h, add_time)values('".$avator["u"]."', '".$avator["w"]."', '".$avator["h"]."', '".time()."')";
        $avator_id = video_db::execute($sql);

        $code = $regdate.$uid;
        $sql = "update t_user set code='".$code."',avator_id=".$avator_id." where uid=".$uid;
        video_db::execute($sql);

        $sql = "insert into t_user_count(uid)values('".$uid."')";
        video_db::execute($sql);
//////////--------------
    }

    $user_import = array();
    $is_d_id=0;
    $is_d_uid=0;
    if(!empty($s_source_id)){//查询抖音id是否存在
        $sql = "select count(*) as num from t_user_import where source_id='".$s_source_id."'";
        $user_import_1 = video_db::fetch($sql);
        if(!empty($user_import_1)){
            $is_d_id=1;//d_id有数据
            $user_import=1;
        }
    }
    if(!empty($s_d_uid)){//如果上一个抖音id查询抖音uid是否存在
        $sql = "select count(*) as num from t_user_import where d_uid='".$s_d_uid."'";
        $user_import_2 = video_db::fetch($sql);
        if(!empty($user_import_2)){
            $is_d_uid=1;//d_uid有数据
            $user_import=1;
        }
    }

    $s_birth=(int)$s_birth;$s_regdate=(int)$s_regdate;$s_like_num=(int)$s_like_num;
    $s_avator_u = !empty($s_avator["u"]) ? $s_avator["u"] : "";
    if(empty($user_import)){//如果此用户不存在，重新生成本站新的导入用户  后续不管
        $sql = "insert into t_user_import(uid,source_id,d_uid,nickname,avator,username,sex,birth,mobile,regdate,sign,add_time,like_num,fans_num)values";
        $sql.= "('".$uid."','".$s_source_id."','".$s_d_uid."','".$s_nickname."','".$s_avator_u."','".$s_mobile."','".$s_sex."','".$s_birth."','".$s_mobile."',
'".$s_regdate."','".$s_sign."','".time()."','".$s_like_num."', '".$s_fans_num."')";
        video_db::execute($sql);
    }else{//todo   待想想
        if($is_d_id){//如果抖音id存在 更新用户信息   并更新抖音uid
            $sql = "update t_user_import set uid=".$uid.",d_uid=".$s_d_uid.",nickname='".$s_nickname."',avator='".$s_avator_u."',username='".$s_mobile."',sex='".$s_sex."',";
            $sql.= "birth='".$s_birth."',mobile='".$s_mobile."',regdate='".$s_regdate."',sign='".$s_sign."',like_num='".$s_like_num."',fans_num='".$s_fans_num."'";
            $sql.= " where source_id='".$s_source_id."'";
            video_db::execute($sql);
        }
        if($is_d_uid){//如果抖音uid存在 不更新抖音uid

            $sql = "update t_user_import set uid=".$uid.",nickname='".$s_nickname."',avator='".$s_avator_u."',username='".$s_mobile."',sex='".$s_sex."',";
            $sql.= "birth='".$s_birth."',mobile='".$s_mobile."',regdate='".$s_regdate."',sign='".$s_sign."',like_num='".$s_like_num."',fans_num='".$s_fans_num."'";
            $sql.= " where d_uid='".$s_d_uid."'";
            video_db::execute($sql);
        }
    }
    video_db::close();
    $res = array("code"=>0, "result"=>array("uid" => $uid), "msg"=>"");
    echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
}catch(PDOException $pe){
    video_db::close();
    file_put_contents('../log/error_'.date('Ymd').'.log',date("Y-m-d H:i:s")."  ".$pe->getMessage()."\r\n",FILE_APPEND);

    $res = array("code"=>-1, "result"=>null, "msg"=>$pe->getMessage());
    echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
}catch (Exception $e){
    video_db::close();
    file_put_contents('../log/error_'.date('Ymd').'.log',date("Y-m-d H:i:s")."  ".$e->getMessage()."\r\n",FILE_APPEND);

    $res = array("code"=>-1, "result"=>null, "msg"=>$e->getMessage());
    echo json_encode($res, JSON_UNESCAPED_UNICODE);exit;
}
